﻿using ContactSMS.Client.Models;
using ContactSMS.Client.Response;
using Newtonsoft.Json;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Xml.Linq;

namespace ContactSMS.Client.Service
{
    public class PhoneRecordService : BaseService
    {
        HttpClient httpClient;

        public PhoneRecordService()
        {
            this.httpClient = new HttpClient();
        }

        public async Task<QResponse<PagedResponse<CallLogModelNew>>> GetPhoneRecordsAsync(long ContactId = 0, int page = 1, int pageSize = 1000)
        {
            var accessToken = await AuthService.GetAccessTokenAsync();
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new InvalidOperationException("Access token is missing. Please log in again.");
            }
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string url = $"{baseUrl}/api/PhoneRecord/GetPhoneRecords?page={page}&pageSize={pageSize}";

            if (ContactId > 0)
            {
                url = url + $"&ContactId={ContactId}";
            }

            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            var resultContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
            var registerResponse = JsonConvert.DeserializeObject<QResponse<PagedResponse<CallLogModelNew>>>(resultContent);
            return registerResponse;
        }

        public async Task<QResponse<CallLogInfoModelNew>> GetByIdAsync(long id)
        {
            var accessToken = await AuthService.GetAccessTokenAsync();
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new InvalidOperationException("Access token is missing. Please log in again.");
            }
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string url = $"{baseUrl}/api/PhoneRecord/GetById/{id}";
            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            var resultContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
            var registerResponse = JsonConvert.DeserializeObject<QResponse<CallLogInfoModelNew>>(resultContent);
            return registerResponse;
        }
    }
}
